
var express = require('express')
var router = express.Router();
var { checkSession, dateFormat } = require('../utils/index')
var { Mvs, Comment } = require('../utils/model');
const { result } = require('underscore');
const { Callbacks } = require('jquery');
const { render } = require('less');

router.get('/test', (req, res) => {
    res.send('test-------')
})

//详情渲染
router.get('/index', (req, res) => {
    checkSession(req, res, () => {
        var { mid } = req.query;
        var obj = {}
        if (mid) {
            obj = { id: mid }
        }
        Mvs.findOne(obj).then(result => {
            res.render('comment', {
                username: req.session.username,
                result
            })
        })

        // const findOneData = function(obj,callback){
        //     Mvs.findOne(obj).then(result=>{
        //         Callbacks(result)
        //     })
        // }

    })

})




//提交评论
router.post('/submit', (req, res) => {
    var query = req.query;
    var body = req.body;
    // console.log(query);
    checkSession(req, res, () => {
        Mvs.findOne({
            id: query.mid
        }).then(result => {
            body.time = new Date();
            body.author = req.session.username;
            body.mid = query.mid;
            body.movie = result;
            // console.log(body.title);
            // if (body.title == '' || body.content == '') {
            //     res.send(`<script>alert('评论为空，请重新评论');location.href='/comment/index?mid=${body.mid}'</script>`)
            // } else {
            //     Comment.insertMany(body).then(result => {
            //         // res.send(`<script>alert('评论成功');location.href='/comment/list?mid=${body.mid}'</script>`)
            //         res.redirect('/comment/list')
            //     })
            // }
            Comment.insertMany(body)
            .then(result=>{
                //  res.send("评论成功...")
                res.redirect("/comment/list")
            })

        })
    })
})

//评论的电影渲染
router.get('/list', (req, res) => {
    checkSession(req, res, () => {
        //分页
        var {
            pageSize,  //每一页的数量
            page       //每一页的页数
        } = req.query;
        pageSize = pageSize * 1 || 10;
        page = page * 1 || 1;
        //总数量
        var total = 0;
        //总页数
        var totalPage = 0;
        Comment.find({}, {})
            .then(data => {
                total = data.length;
                //总的页数=总条数/每页的10条，向上取整
                totalPage = Math.ceil(total / pageSize);
                page = page < 1 ? 1 : page;
                page = page > totalPage ? totalPage : page;

                Comment.find({}, {})
                    //跳过多少条
                    .skip((page - 1) * pageSize)
                    //限制多少条
                    .limit(pageSize)
                    .sort({ _id: -1 })
                    .then(result => {
                        result = result.map(item => {
                            item = { ...item._doc, time: dateFormat(item.time) }
                            return item
                        })
                        res.render('list', {
                            username: req.session.username,
                            result,
                            total,
                            page,
                            pageSize,
                            totalPage
                        })
                    })
            })
    })
})


//当前电影的所有评论
router.get('/moviepin', (req, res) => {
    checkSession(req, res, () => {
        var { mid } = req.query;
        Comment.find({
            mid
        }, {})
            .sort({ _id: -1 })
            .then(result => {
                result = result.map(item => {
                    item = { ...item._doc, time: dateFormat(item.time) }
                    return item
                })
                res.render('moviepin', {
                    result,
                    movie: result[0].movie,
                    username: req.session.username
                })
            })
    })
})


//用户所有评论
router.get('/my', (req, res) => {
    checkSession(req, res, () => {
        var { author } = req.query;
        Comment.find({
            author
        }).sort({ _id: -1 })
            .then(result => {
                result = result.map(item => {
                    item = { ...item._doc, time: dateFormat(item.time) }
                    return item
                })
                res.render('my', {
                    result,
                    author,
                    username: req.session.username
                })
            })
    })
})


//回复评论
router.get('/detail', (req, res) => {
    checkSession(req, res, () => {
        var { _id } = req.query;
        console.log(_id);
        Comment.findOne({
            _id
        })
            .then(result => {
                console.log(result);
                result = { ...result._doc, time: dateFormat(result.time) }
                res.render('detail', {
                    result,
                    username: req.session.username
                })

            })

    })
})


//回复子评论
router.post('/answersubmit', (req, res) => {
    checkSession(req, res, () => {
        var {
            _id,
            subtitle
        } = req.body;
        Comment.findOne({
            _id,

        }).then(data => {
            var answer = data.answer || [];
            answer.push({
                subtitle,
                id: answer.length,
                author: req.session.username,
                time: dateFormat(new Date())
            })
            Comment.updateMany({
                _id
            }, {
                $set: {
                    answer
                }
            }).then(result => {
                res.json({
                    code: 200,
                    msg: '回复评论成功',
                    result,
                    type: 1
                })
            })
        })
    })
})

//删除评论
router.post('/delsubmit', (req, res) => {
    checkSession(req, res, () => {
        var { _id } = req.body;
        Comment.remove({
            _id
        }).then(result => {
            res.json({
                code: 200,
                msg: '删除评论成功',
                result,
                type: 1
            })
        })
    })
})

//修改评论
router.get('/updata',(req,res)=>{
    checkSession(req, res, () => {
        var {_id} = req.query;
        Comment.findOne({
            _id
        }).then(result=>{
            result = { ...result._doc, time: dateFormat(result.time) }
            res.render('updata', {
                result,
                movie:result.movie,
                username: req.session.username
            })
        })
    })
})

router.post('/updatesumbit',(req,res)=>{
    checkSession(req, res, () => {
        var body = req.body;
        body.time = new Date();
        Comment.updateMany({
            _id:req.query._id
        },{
            $set:body
        }).then(result=>{
            res.redirect('/comment/list')
        }).catch(err=>{

        })
    })
})


var multiparty = require("multiparty")
var fs = require("fs")
// 上传图片
router.post("/uploadImg",(req,res)=>{
    const form = new multiparty.Form();
    form.encoding = "utf-8"
    form.uploadDir = "./uploadtemp"  // 临时文件中转站
    form.maxFilesSize = 8*1024*1024;  // 2M 
    form.parse(req,function(err,fields,files){
        if(err) {
            console.log(err)
            res.send("<script>alert('图片过大,请重新上传');location.reload()'</script>")
        }
        var uploadUrl = "/images/upload/",
        file  = files['filedata'], // 图片信息
        originalFilename = file[0].originalFilename, // 文件名
        tempath = file[0].path;
        var timestamp = new Date().getTime(); // 时间戳
        uploadUrl += timestamp+originalFilename;  // 1.jpg ==> 15112341231.jpg
        var newPath = "./public"+uploadUrl;  // 最后路径 
        var fileRead = fs.createReadStream(tempath);
        var fileWrite = fs.createWriteStream(newPath);
        fileRead.pipe(fileWrite);
        fileWrite.on("close",()=>{
            fs.unlinkSync(tempath);
            res.json({
                err:"",
                msg:uploadUrl
            })
        })
    })
})

//在线聊天
router.get('/chat',(req,res)=>{
    checkSession(req, res, () => {
        res.render('chat',{
            username:req.session.username
        })
    })
})


module.exports = router